package com.gexin.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

@SuppressWarnings("deprecation")
public class HttpKit {
	
	/*	http请求	*/
	public static String post(String url,Map<String, String> param){
    	String body = null;
		HttpClient httpClient = new DefaultHttpClient();  
        try {
            // Post请求  
            HttpPost httppost = new HttpPost(url);
            // 设置参数  
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (String key : param.keySet()) {
            	params.add(new BasicNameValuePair(key, param.get(key)));
			}
            httppost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));   
            // 发送请求
            HttpResponse httpresponse = httpClient.execute(httppost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            if (entity != null) {
                body = EntityUtils.toString(entity);
                entity.consumeContent();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;  
    }
	
	public static String post(String url,String params){
    	String body = null;
		HttpClient httpClient = new DefaultHttpClient();  
        try {
            // Post请求  
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Content-Type", "application/json;charset=utf-8");
            httppost.setEntity(new StringEntity(params,"utf-8"));   
            // 发送请求
            HttpResponse httpresponse = httpClient.execute(httppost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            if (entity != null) {
                body = EntityUtils.toString(entity);
                entity.consumeContent();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;  
    }

    /**
     * HTTPS的Get请求方式
     */
    public static String doGet(String strUrl){
        String returnStr = null; // 返回结果定义
        URL url = null;
        HttpURLConnection httpURLConnection = null;
        try {
            url = new URL(strUrl);
            Properties systemProperties =System.getProperties();
            systemProperties.setProperty("http.proxyHost","");
            systemProperties.setProperty("http.proxyPort","");

            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("cache-control", "no-store, no-cache, must-revalidate");
            httpURLConnection.setRequestProperty("content-encoding", "gzip");
            httpURLConnection.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
            httpURLConnection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
            httpURLConnection.setRequestProperty("user-agent","Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET"); // post方式
            httpURLConnection.connect();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));

            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }

    /**
     * HTTPS的Post请求方式
     * @param strUrl 访问地址
     * @param param 参数字符串
     * */
    public static String doPost(String strUrl, String param) {
        String returnStr = null; // 返回结果定义
        URL url = null;
        HttpURLConnection httpURLConnection = null;
  
        try {
            url = new URL(strUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST"); // post方式
            httpURLConnection.connect();
            //System.out.println("ResponseCode:" + httpURLConnection.getResponseCode());
            //POST方法时使用
            byte[] byteParam = param.getBytes("UTF-8");
            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
            out.write(byteParam);
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
  
            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }
    //将map型转为请求参数型
    public static String urlencode(Map<String,String> data) {
        StringBuilder param_str = new StringBuilder();
        for (Entry<String, String> i : data.entrySet()) {
            try {
            	param_str.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue(),"UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return param_str.toString();
    }
}
